package com.wxsm.wechat.controller;

import com.wxsm.wechat.core.aop.NeedLogin;
import com.wxsm.wechat.core.exception.ExceptionEnum;
import com.wxsm.wechat.core.exception.ServiceException;
import com.wxsm.wechat.model.CommonJsonResult;
import com.wxsm.wechat.service.FileService;
import com.wxsm.wechat.util.ActionUtil;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 公共操作
 * Created with Yang Huan
 * Date: 2017/5/24
 * Time: 15:09
 */
@Controller
@RequestMapping(value = "/common")
@AllArgsConstructor
public class CommonController {

    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);

    private final FileService fileService;

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    @NeedLogin
    public CommonJsonResult uploadFile(@RequestParam("file") MultipartFile file) throws ServiceException {
        String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("/");
        stringBuilder.append(ActionUtil.getOpenId());
        stringBuilder.append("/");
        stringBuilder.append(System.currentTimeMillis());
        stringBuilder.append(".");
        stringBuilder.append(extension);
        String cosPath = stringBuilder.toString();
        try {
            String imageUrl = fileService.uploadImage(cosPath, file.getInputStream(), extension);
            return CommonJsonResult.success().putData("imageUrl", imageUrl);
        } catch (IOException e) {
            logger.error("上传文件异常", e);
            throw new ServiceException(ExceptionEnum.UPLOAD_ERROR);
        }
    }

}
